package com.patchmanage.back.controller;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patchmanage.back.annotation.LoginValidate;
import com.patchmanage.back.annotation.OperLog;
import com.patchmanage.back.config.Constants;
import com.patchmanage.back.entity.Admin;
import com.patchmanage.back.entity.Role;
import com.patchmanage.back.redis.JedisTemplate;
import com.patchmanage.back.result.Result;
import com.patchmanage.back.service.IAdminService;
import com.patchmanage.back.service.IDepartmentGroupService;
import com.patchmanage.back.service.IRoleService;
import com.patchmanage.back.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * admin 控制器
 * </p>
 *
 * @author huizhao
 * @since 2021-03-20
 */

@Api(value=" 管理员 controller",tags={"管理员 Api"})
@RestController
@RequestMapping("/back/admin")
public class AdminController {
    @Autowired
    private IAdminService adminService;

    @Autowired
    private JedisTemplate<String> jedisTemplate;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IDepartmentGroupService departmentGroupService;

    /**
     * @param map
     * @describe：登录接口  
     * @author：HuiZhao  
     * @createTime：2019年10月11日 下午3:30:12
     * @return    
     */
    @ApiOperation(value = "登录接口", notes = "登录接口")
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "username", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "password", value = "password", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "verificationCode", value = "verificationCode", required = false, dataType = "String", paramType = "body")
    })
    @LoginValidate
    @OperLog(operModul="管理员",operDesc="管理员登录")
    public Result<Dict> login(@ApiIgnore @RequestBody Dict map) {
        return Result.success(adminService.login(map));
    }

    /**
     * @param dict
     * @describe：获取单个用户接口  
     * @author：HuiZhao  
     * @createTime：2019年10月11日 下午3:30:12
     * @return    
     */
    @ApiOperation(value = "获取单个用户接口", notes = "获取单个用户接口")
    @RequestMapping(value = "findByToken", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "String", paramType = "body")
    })
    @LoginValidate
    public Result<Map<String,Object>> findByToken(@ApiIgnore @RequestBody Dict dict) {
        Admin admin = adminService.getByToken(dict);
        Map<String,Object> returnMap = new HashMap<String, Object>();
        if(admin != null ){
            Role role = roleService.getById(admin.getRole());
            returnMap.put("admin",admin);
            returnMap.put("role",role);
        }
        return Result.success(returnMap);
    }

    /**
     * @param entity
     * @describe：注册接口  
     * @author：HuiZhao  
     * @createTime：2019年10月11日 下午3:30:12
     * @return    
     */
    @ApiOperation(value = "注册接口", notes = "注册接口")
    @RequestMapping(value = "registe", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "username", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "nickname", value = "nickname", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "password", value = "password", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "role", value = "role", required = true, dataType = "Integer", paramType = "body")
    })
    @LoginValidate
    @OperLog(operModul="管理员",operDesc="注册")
    public Result<Boolean> registe(@ApiIgnore @RequestBody Admin entity) {
        return Result.success(adminService.registe(entity));
    }

    /**
     * @param map
     * @describe：获取用户列表接口  
     * @author：HuiZhao  
     * @createTime：2019年10月11日 下午3:30:12
     * @return    
     */
    @ApiOperation(value = "获取用户列表接口", notes = "获取用户列表接口")
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "phone", required = false, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "nickName", value = "nickName", required = false, dataType = "String", paramType = "body")
    })
    @LoginValidate
    public Result<Collection<Admin>> list(@ApiIgnore @RequestBody Map<String, Object> map) {
        return Result.success(adminService.listByMap(map));
    }

    /**
     * @param dict
     * @describe：获取用户列表接口  
     * @author：HuiZhao  
     * @createTime：2019年10月11日 下午3:30:12
     * @return    
     */
    @ApiOperation(value = "获取用户列表接口分页", notes = "获取用户列表接口")
    @RequestMapping(value = "listByPage", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "pageNo", required = true, dataType = "Integer", paramType = "body"),
            @ApiImplicitParam(name = "pageSize", value = "pageSize", required = true, dataType = "Integer", paramType = "body")
    })
    @LoginValidate
    public Result<IPage<Admin>> listByPage(@ApiIgnore  @RequestBody Dict dict) {
        Integer pageNo = dict.getInt("pageNo");
        Integer pageSize = dict.getInt("pageSize");
        Page page = new Page(pageNo,pageSize);
        return Result.success(adminService.page(page));
    }

    /**
     * @param entity
     * @describe：新增或编辑用户接口  
     * @author：HuiZhao  
     * @createTime：2019年10月11日 下午3:30:12
     * @return    
     */
    @LoginValidate
    @ApiOperation(value = "新增或编辑用户接口", notes = "新增或编辑用户接口")
    @RequestMapping(value = "addOrUpdate", method = RequestMethod.POST)
    @OperLog(operModul="管理员",operDesc="新增或编辑用户")
    public Result<Boolean> addOrUpdate(@RequestBody Admin entity) {

        if(entity.getId() == null){
            entity.setPassword(MD5Util.md5(entity.getPassword()));
        }
        if(entity.getRole() != null){
            Role role = roleService.getById(entity.getRole());
            if(role != null){
                entity.setRoleName(role.getName());
            }
        }
        /*if(entity.getDepartmentGroupIds().equals("all")){
            List<DepartmentGroup> departmentGroupList =  departmentGroupService.list();
            if(departmentGroupList.size() > 0){
                List<String> ids = CollUtil.getFieldValues(departmentGroupList, "id",String.class);
                String str = Joiner.on(",").join(ids);
                entity.setDepartmentGroupIds(str);
            }
        }*/
        return Result.success(adminService.saveOrUpdate(entity));
    }

    /**
     * @param dict
     * @describe：删除用户接口  
     * @author：HuiZhao  
     * @createTime：2019年10月11日 下午3:30:12
     * @return    
     */
    @LoginValidate
    @ApiOperation(value = "删除用户接口", notes = "删除用户接口")
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @OperLog(operModul="管理员",operDesc="删除用户")
    public Result<Boolean> delete(@RequestBody Dict dict) {
        String[] idsArray = dict.getStr("ids").split(",");
        List<String> idsList= Arrays.asList(idsArray);
        if(idsList.contains("1")){
            return null;
        }
        return Result.success(adminService.removeByIds(idsList));
    }

    /**
     * @param dict
     * @describe：重置用户密码  
     * @author：HuiZhao  
     * @createTime：2019年10月11日 下午3:30:12
     * @return    
     */
    @LoginValidate
    @ApiOperation(value = "重置密码", notes = "重置密码接口")
    @RequestMapping(value = "resetPassword", method = RequestMethod.POST)
    @OperLog(operModul="管理员",operDesc="重置密码")
    public Result<Boolean> resetPassword(@ApiIgnore @RequestBody Dict dict) {

        String ids = dict.getStr("ids");
        List<String> idlist = Arrays.asList(ids.split(","));
        UpdateWrapper<Admin> u = new UpdateWrapper();
        u.in("id",idlist);
        Admin a = new Admin();
        a.setPassword(MD5Util.md5("111111"));
        adminService.update(a,u);
        return Result.success(adminService.update(a,u));
    }

    /**
     * @param dict
     * @describe：修改密码用户接口  
     * @author：HuiZhao  
     * @createTime：2019年10月11日 下午3:30:12
     * @return    
     */
    @LoginValidate
    @ApiOperation(value = "修改密码", notes = "修改密码接口")
    @RequestMapping(value = "updatePassword", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "username", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "password", value = "password", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "password1", value = "password1", required = true, dataType = "String", paramType = "body")
    })
    @OperLog(operModul="管理员",operDesc="修改密码")
    public Result<Boolean> updatePassword(@ApiIgnore @RequestBody Dict dict) {
        return Result.success(adminService.setNewPassword(dict));
    }


    /**
     * @describe：删除用户接口  
     * @author：HuiZhao  
     * @createTime：2019年10月11日 下午3:30:12
     * @return    
     */
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    @GetMapping(value = "getVerifyCode")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
        adminService.getVerifyCode(request, response);
    }

    /**
     * @describe：注销登录
     * @author：HuiZhao  
     * @createTime：2019年10月11日 下午3:30:12
     * @return    
     */
    @ApiOperation(value = "注销登录", notes = "注销登录")
    @PostMapping(value = "logout")
    @OperLog(operModul="管理员",operDesc="注销登录")
    @LoginValidate
    public void logout(@ApiIgnore @RequestBody Dict dict) throws Exception{
        jedisTemplate.del(Constants.userToken + dict.getStr("token"));
    }
}
